<template>
    <div>
        <vxe-toolbar custom  ref="toolbarRef" >
            <template #buttons>
                <el-button
                        type="primary"
                        icon="el-icon-plus"
                        @click="handleAdd"
                        v-if="this.editable"
                >
                    新 增
                </el-button>
            </template>
            <template #tools>

                <el-tooltip content="清空筛选" placement="top">
                    <vxe-button  icon="vxe-icon-delete" class="tool-btn" @click="$refs.tableRef.clearFilter()" circle></vxe-button>
                </el-tooltip>

             <vxe-button  icon="vxe-icon-refresh" class="tool-btn" @click="refresh" circle style="margin-right: 12px;"></vxe-button>
      </template>
        </vxe-toolbar>
        <vxe-grid
                v-bind="gridOptions"
                id="tableRef"
                ref="tableRef"
                class="mytable-scrollbar"
                :data="list"
                :customConfig="customConfig"
                :menu-config="menuConfig"
                :edit-rules="validRules"
                :scroll-y="{enabled: true, gt: 10}"
                :tooltip-config="{ zIndex: 9999 }"
                :edit-config="{
                    trigger: 'click',
                    mode: 'row',
                    showStatus: true,
                    showIcon: true,
                    autoClear:true,
                    beforeEditMethod:beforeEdit}"
                @edit-closed="editClosedEvent"
                @edit-actived="editActivedEvent"
                @menu-click="contextMenuClickEvent"
        >
            <template #nation_default="scope">
                {{ scope.row.nation}}
            </template>
            <template #nation_edit="scope">
                <vxe-input v-model="scope.row.nation" type="text" placeholder="请输入国家"></vxe-input>
            </template>

            <!--<template #province_default="scope">-->
                <!--{{ scope.row.provinceName || formatProvince(scope.row.province)}}-->
            <!--</template>-->
            <!--<template #province_edit="scope">-->
                <!--<el-select v-model="scope.row.province" filterable clearable type="string" transfer  @change="selectProvince">-->
                    <!--<el-option-->
                            <!--v-for="item in provinceList"-->
                            <!--:key="item.code"-->
                            <!--:value="item.code"-->
                            <!--:label="item.name"/>-->
                <!--</el-select>-->
            <!--</template>-->

            <!--<template #city_default="scope">-->
                <!--{{ scope.row.cityName || formatCity(scope.row.city)}}-->
            <!--</template>-->
            <!--<template #city_edit="scope">-->
                <!--<el-select v-model="scope.row.city" clearable type="string" transfer>-->
                    <!--<el-option-->
                            <!--v-for="item in cityList"-->
                            <!--:key="item.code"-->
                            <!--:value="item.code"-->
                            <!--:label="item.name"></el-option>-->
                <!--</el-select>-->
            <!--</template>-->

            <template #btn_default="scope">
                <template v-if="!isActiveStatus(scope.row) && this.editable">
                    <!--<el-tooltip content="修改" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleUpdate(row)"-->
                    <!--&gt;修改-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                    <el-tooltip content="删除" placement="top">
                        <el-button
                                icon="el-icon-delete"
                                link
                                size="small"
                                type="primary"
                                @click="handleDelete(scope.row)"
                        ></el-button>
                    </el-tooltip>
                </template>
                <template v-else>
                    <!--<el-tooltip content="保存" placement="top">-->
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--type="primary"-->
                    <!--@click="handleSaveRow(row)"-->
                    <!--&gt;保存-->
                    <!--</el-button>-->
                    <!--</el-tooltip>-->
                    <template v-if="!scope.row.id && this.editable">
                        <el-tooltip content="取消" placement="top">
                            <el-button
                                    size="small"
                                    @click="handleDelete(scope.row)"
                            >取消
                            </el-button>
                        </el-tooltip>
                    </template>
                </template>
            </template>
        </vxe-grid>

         <!--<div style="margin-top:20px">-->
            <!--<vxe-pager -->
            <!--v-model:current-page="page.currentPage" -->
            <!--v-model:page-size="page.pageSize" -->
            <!--:total="page.total"-->
            <!--@page-change='pageChange'-->
            <!--background-->
            <!--:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes',  'Total']"-->
             <!--size="small" -->
             <!--/>-->
         <!--</div>-->

    </div>
</template>

<script>
    import {getList, getDetail, add, update, remove,findList} from "@/api/anwise/customer/customer_factory";
    import {getDetail as getCustomerDetail} from "@/api/anwise/customer/customer";

    import {mapGetters} from "vuex";
    import {VXETable} from 'vxe-table'
    import {getDictionary} from "@/api/system/dict"
    import {select} from "@/api/base/region";
    import {Pattern} from "@/utils/validate.js";

    export default {
        components: {

        },
        data() {
            return {
                isEdit:false,
                iconSearch:true,
                customerId:undefined,
                provinceList:[],
                cityList:[],
                editable:true,
                props: {
                    customerId: {
                        type: String,
                        default: ""
                    },
                },
                list: [],
                customConfig: {
                    storage: true,
                    checkMethod({column}) {
                        if (['facName'].includes(column.field)) {
                            return false
                        }
                        return true
                    },
                },
                menuConfig: {},
                form: {},
                query: {},
                loading: true,
                data: [],
                selectionList: [],
                page: {
                    pageSize: 20,
                    currentPage: 1,
                    total: 0
                },
                subVisible: false,
                direction: 'rtl',
                customerName: "安伟客户表",
                customerTypeList: [],
                nameOptions: [{data: null}],
                validRules: {
                    facName: [
                        {required: true, message: '收货工厂必须填写',trigger:'change'}
                    ],
                    facAddr: [
                        {required: true, message: '收货地址必须填写',trigger:'change'}
                    ],
                    // contact: [
                    //     {required: true, message: '联系人必须填写',trigger:'change'}
                    // ],
                    // contactPhone: [
                    //     {required: true, message: '联系电话必须填写',trigger:'change'}
                    // ],
                    contactEmail: [
                        {required: false,pattern: Pattern.email, message: '邮件格式错误',trigger:'change'}
                    ]
                },
                gridOptions: {
                    height: '400px',
                    border: true,
                    showOverflow: true,
                    keepSource: true,
                    size: "medium",
                    rowConfig: {
                        // keyField: 'id',
                        isHover: true
                    },
                    columnConfig: {
                        resizable: true
                    },
                    // editRules: ,
                    columns: [
                        // {type: 'checkbox', width: 50, fixed:'left', visible: true},
                        // {type: 'seq', width: 50, fixed:'left', align: "center"},
                        {
                            title: "收货工厂",
                            field: "facName",
                            fixed:'left',
                            minWidth: 350,
                            maxlength:1000,
                            editRender:{name: 'input', attrs: {placeholder: '请输入收货工厂'}},
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "收货地址",
                            field: "facAddr",
                            minWidth: 750,
                            editRender: {name: 'input', attrs: {placeholder: '请输入收货地址'}},
                            filters: [{ data: '' }],
                            filterRender: { name: 'FilterInput'}
                        },
                        {
                            title: "联系人",
                            field: "contact",
                            minWidth: 250,
                            editRender: {name: 'input', attrs: {placeholder: '请输入联系人'}},
                        },
                        {
                            title: "联系人部门",
                            field: "contactDept",
                            minWidth: 120,
                            editRender: {name: 'input', attrs: {placeholder: '请输入联系人部门'}},
                            // slots: {edit: 'fullBox_edit', default: 'fullBox_default'}
                        },
                        {
                            title: "联系人电话",
                            field: "contactPhone",
                            minWidth: 200,
                            editRender: {name: 'input', attrs: {placeholder: '请输入联系人电话'}},
                            // slots: {edit: 'fullBox_edit', default: 'fullBox_default'}
                        },
                        {
                            title: "联系人邮箱",
                            field: "contactEmail",
                            width: 200,
                            editRender:{name: 'input', attrs: {placeholder: '请输入联系人邮箱'}},
                            // slots: {edit: 'bankId_edit', default: 'bankId_default'}
                        },
                        {
                            title: "国家",
                            field: "nation",
                            width: 150,
                            editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                            slots: {edit: 'nation_edit', default: 'nation_default'}
                        },
                        // {
                        //     title: "省份",
                        //     field: "province",
                        //     width: 120,
                        //     editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                        //     slots: {edit: 'province_edit', default: 'province_default'}
                        // },
                        // {
                        //     title: "城市",
                        //     field: "city",
                        //     width: 120,
                        //     editRender: {placeholder: '请输入...', autofocus: '.vxe-input--inner', autoselect: true},
                        //     slots: {edit: 'city_edit', default: 'city_default'}
                        // },
                        // {
                        //     title: "邮政编码",
                        //     field: "postcode",
                        //     width: 120,
                        //     editRender: {name: 'input', attrs: {placeholder: '请输入邮政编码'}},
                        //     // slots: {edit: 'postcode_edit', default: 'postcode_default'}
                        // },
                        // {
                        //     title: "收货人",
                        //     field: "consignee",
                        //     width: 120,
                        //     editRender: {name: 'input', attrs: {placeholder: '请输入收货人'}},
                        //     // slots: {edit: 'consignee_edit', default: 'consignee_default'}
                        // },
                        {
                            title: "箱唛备注",
                            field: "cartonMarkRemark",
                            width: 350,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                            // slots: {default: 'cartonMarkRemark_default'}
                        },
                        {
                            title: "销售备注",
                            field: "salesRemark",
                            width: 350,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                            // slots: {default: 'salesRemark_default'}
                        },
                        {
                            title: "生产备注",
                            field: "prodRemark",
                            width: 350,
                            editRender:{ name:'EditDownTextarea',maxlength:2000,props:{maxlength:2000,rows:5,showWordCount:true}},
                            // slots: {default: 'prodRemark_default'}
                        },
                        {
                            title: "创建人员",
                            field: "createUserName",
                            width: 100,
                        },
                        {
                            title: "创建时间",
                            field: "createTime",
                            width: 150,
                        },
                        {
                            field: 'btn',
                            title: '操作',
                            minWidth: 120,
                            align: "center",
                            fixed: "right",
                            visible: true,
                            slots: {default: 'btn_default'}
                        }
                    ]
                },

            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.customer_add, false),
                    viewBtn: this.validData(this.permission.customer_view, false),
                    delBtn: this.validData(this.permission.customer_delete, false),
                    editBtn: this.validData(this.permission.customer_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            },
            subIds() {
                let ids = [];
                this.selectionListSub.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
            this.isEdit = false;
            this.initDict();
            this.disabledCommit(false);
            this.menuConfig = {
                header: {
                    options: [
                        [
                            {code: 'hideColumn', name: '隐藏列', disabled: false},
                            {code: 'showAllColumn', name: '取消所有隐藏列', disabled: false},
                        ],
                    ],
                },
                body: {
                    options: [
                        [
                            {
                                code: 'copy',
                                name: '复制',
                                prefixIcon: 'vxe-icon-copy',
                                disabled: false,
                            },
                        ],
                    ],
                },
                visibleMethod({options, column}) {
                    const isDisabled = !column
                    options.forEach((list) => {
                        list.forEach((item) => {
                            item.disabled = isDisabled
                        })
                    })
                    return true
                },
            }
            this.$nextTick(() => {
                console.log(this.$refs.tableRef)
                console.log(this.$refs.toolbarRef)
                this.$refs.tableRef.connect(this.$refs.toolbarRef);
            })
        },
        methods: {
            refresh(){
               this.page = {
                   pageSize: 20,
                   currentPage: 1,
               }
               this.query = {}
               this.query.customerId = this.customerId
               this.onLoad(this.page)
            },
            pageChange(e){
               this.page = {
                    pageSize: e.pageSize,
                    currentPage: e.currentPage,
               }
               this.onLoad(this.page)
            },
            beforeEdit({ row, rowIndex, column, columnIndex }) {
              if (this.editable) {

              }
              return this.editable;
            },
            // formatCountry(val) {
            //     if (val) {
            //         return '中国'
            //     }
            //      return val;
            // },
            // formatProvince(val) {
            //     let value = "";
            //     if (this.provinceList) {
            //         this.provinceList.forEach(item => {
            //             if (item.code === val) {
            //                 value = item.name;
            //                 return;
            //             }
            //         })
            //     }
            //     return value;
            // },
            // formatCity(val) {
            //     let value = "";
            //     if (this.cityList) {
            //         this.cityList.forEach(item => {
            //             if (item.code === val) {
            //                 value= item.name;
            //                 return;
            //             }
            //         })
            //     }
            //     return value;
            // },
            // selectCountry(val) {
            //     select(val.value).then(res => {
            //         this.provinceList= res.data.data;
            //     })
            // },
            // selectProvince(val) {
            //     console.log(val.select);
            //     select(val.value).then(res => {
            //         this.cityList= res.data.data;
            //     })
            // },
            isActiveStatus(row) {
                const $table = this.$refs.tableRef
                if ($table) {
                    return $table.isEditByRow(row)
                }
            },
            handleAdd() {
                this.isEdit = true;
                const $table = this.$refs.tableRef
                if (!$table.getEditRecord()) {
                    console.log(this.tableRef)
                    if ($table) {
                        const obj = $table.insertAt({}, -1).then(res => {
                            $table.setEditCell(res.row, 'facName');
                        })
                        console.log(obj)
                        // this.searchShow = false
                        // this.iconSearch = false
                    }
                }
            },
            contextMenuClickEvent(data) {
                const menu = data.menu;
                const row = data.row;
                const column = data.column;
                const $table = this.$refs.tableRef
                if ($table) {
                    switch (menu.code) {
                        case 'hideColumn':
                            $table.hideColumn(column)
                            break
                        case 'showAllColumn':
                            $table.resetColumn(true)
                            break
                        case 'copy':
                            // if (XEClipboard.copy(row[column.field])) {
                            //   ElMessage.success('保存成功')
                            // }
                            // ElMessage.success('复制成功')
                            break
                        case 'reload':
                            //  findList()
                            break
                        case 'insertAt':
                            $table.insertAt({}, row || -1).then(({row}) => {
                                $table.setEditCell(row, column || 'name')
                            })
                            break
                        case 'remove':
                            $table.remove(row)
                            break
                        case 'save':
                            // ElMessage.success('保存成功')
                            break
                    }
                }
            },
            disabledCommit(data) {
                this.$emit("disabledCommit",data);
            },
            editActivedEvent(row){//激活单元格事件
                this.isEdit = true;
                this.disabledCommit(true);
            },
            async editClosedEvent(row) {
                console.log(row)
                const $table = this.$refs.tableRef;
                $table.clearValidate();
                this.disabledCommit(false);
                // const $table = this.$refs.tableRef
                // console.log($table.getTableData().fullData);
                // const err = await this.validEvent(row.row);
                // if (err) {
                //     return
                // }
                // if (!!this.customerId && this.customerId !== '') {
                //     row.row.customerId = this.customerId;
                //     update(row.row).then(res => {
                //         if (res && res.data.success) {
                //             this.$message({
                //                 type: "success",
                //                 message: res.data.msg ? res.data.msg : "保存成功!"
                //             });
                //         } else {
                //             this.$message({
                //                 type: "error",
                //                 message: res.data.msg ? res.data.msg : "保存失败!"
                //             });
                //         }
                //     });
                // }
            },
            async handleSaveRow(row) {
                const err = await this.validEvent(row);
                if (err) {
                    return
                }

            },
            async validEvent(row) {
                const $table = this.$refs.tableRef
                const errMap = await $table.validate(row).catch(errMap => errMap)
                return errMap;

            },
            setData(editable,customerId) {
                // if (list)
                //     this.list = list;

                if(customerId){
                    this.query.customerId = customerId
                    this.customerId = customerId
                }
                console.log("aaaaaa", this.customerId)
               // this.customerId = customerId
                this.onLoad(this.page)

                this.editable = editable;
                console.log(this.editable);
            },
            formatType(value) {
                let value2 = "";
                this.customerTypeList.forEach(res => {
                    if (value === res.dictKey) {
                        value2 = res.dictValue;
                    }
                });
                return value2
            },
            initDict() {
                getDictionary({code: 'customer_type'}).then(res => {
                    this.customerTypeList = res.data.data;
                });
            },
            // 主表模块
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    window.console.log(error);
                    loading();
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            async handleDelete(row) {
                const $table = this.$refs.tableRef
                if (row.id) {
                    this.$confirm('是否确认删除?', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        console.log(row.id);
                        return remove(row.id);

                    }).then(() => {
                        $table.remove(row)
                    })
                } else {
                    $table.remove(row)
                }
            },
            // handleDelete() {
            //   if (this.selectionList.length === 0) {
            //     this.$message.warning("请选择至少一条数据");
            //     return;
            //   }
            //   this.$confirm("确定将选择数据删除?", {
            //     confirmButtonText: "确定",
            //     cancelButtonText: "取消",
            //     type: "warning"
            //   })
            //     .then(() => {
            //       return remove(this.ids);
            //     })
            //     .then(() => {
            //       this.onLoad(this.page);
            //       this.$message({
            //         type: "success",
            //         message: "操作成功!"
            //       });
            //       this.$refs.crud.toggleSelection();
            //     });
            // },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                if(this.$refs.crud)  this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            onLoad(page, params = {}) {
                if (this.$refs.tableRef.getInsertRecords().length>0 || this.$refs.tableRef.getRemoveRecords().length>0 ||
                    this.$refs.tableRef.getUpdateRecords().length>0) {
                    this.$confirm("搜索会丢失本次新增/编辑的数据，确定继续吗?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    })
                        .then(() => {
                            this.loading = true;
                            console.log('aaaaaaaaaaaa', this.query)
                            findList(Object.assign(params, this.query)).then(res => {
                                const data = res.data.data;
                                // this.page.total = data.total;
                                this.list = data;
                                this.loading = false;
                                this.selectionClear();
                                this.isEdit = false;
                            });
                        })
                }else {
                    this.loading = true;
                    console.log('aaaaaaaaaaaa', this.query)
                    findList(Object.assign(params, this.query)).then(res => {
                        const data = res.data.data;
                        // this.page.total = data.total;
                        this.list = data;
                        this.loading = false;
                        this.selectionClear();
                        this.isEdit = false;
                    });
                }
            },

        }
    };
</script>

<style scoped>
:deep(.vxe-pulldown.size--medium){
    z-index: 99999 !important;
}
.vxe-table--tooltip-wrapper {
  z-index: 10000 !important;
}
:deep(.vxe-table--fixed-right-wrapper){
    z-index: 99999 !important;
}
</style>
